<?php

namespace app\api\controller\user;

use think\Controller;

class Auth extends Controller{
    public function __construct()
    {
        parent::__construct();

        $this->UserModel=model('User.User');
        $this->RegionModel=model('Region');
    }

    public function login(){
        if($this->request->isPost()){
            $code=$this->request->param('code','');
            if(!$code){
                $this->error('临时授权失败');
                exit;
            }

            // 调用微信接口
            $result=$this->code2ession($code);
            $openid=isset($result['openid']) ? trim($result['openid']) : '';
            if(empty($openid)){
                $this->error('微信授权失败');
                exit;
            }

            // 根据openid判断是否有绑定用户，有绑定用户就将用户信息返回，没绑定就去绑定
            $User=$this->UserModel->where(['openid'=>$openid])->find();

            if($User){
                $data=[
                    'id'=>$User['id'],
                    'openid'=>$User['openid'],
                    'email'=>$User['email'],
                    'nickname'=>$User['nickname'],
                    'avatar'=>$User['avatar_cdn'],
                    'sex'=>$User['sex'],
                    'sex_text'=>$User['sex_text'],
                    'province'=>$User['province'],
                    'city'=>$User['city'],
                    'district'=>$User['district'],
                    'createtime'=>$User['createtime'],
                    'content'=>$User['content'],
                    'point'=>$User['point'],
                    'vip'=>$User['vip'],
                    'auth'=>$User['auth'],
                    'cover'=>$User['cover_cdn'],
                    'region'=>explode('-', $User['region']),
                    'region_text'=>$User['region']
                ];

                $this->success('登录成功',null,$data);
                exit;
            }else{
                // 授权成功了，但是没有关联用户
                $this->success('请先关联账号','/pages/user/bind',null);
                exit;
            }
        }
    }

    // 微信小程序绑定，如果不存在就注册，如果存在就绑定
    public function bind(){
        if($this->request->isPost()){
            $code=$this->request->param('code','');

            if(!$code){
                $this->error('临时授权失败');
                exit;
            }

            $password=$this->request->param('password','');
            if(empty($password)){
                $this->error('密码不能为空');
                exit;
            }

            // 调用微信接口
            $result=$this->code2ession($code);
            $openid=isset($result['openid']) ? trim($result['openid']) : '';
            if(empty($openid)){
                $this->error('微信授权失败');
                exit;
            }

            // 根据openid判断是否有绑定用户，有绑定用户就将用户信息返回，没有就去绑定
            $User=$this->UserModel->where(['openid'=>$openid])->find();

            if($User){
                $data=[
                    'id'=>$User['id'],
                    'openid'=>$User['openid'],
                    'email'=>$User['email'],
                    'nickname'=>$User['nickname'],
                    'avatar'=>$User['avatar_cdn'],
                    'sex'=>$User['sex'],
                    'sex_text'=>$User['sex_text'],
                    'province'=>$User['province'],
                    'city'=>$User['city'],
                    'district'=>$User['district'],
                    'createtime'=>$User['createtime'],
                    'content'=>$User['content'],
                    'point'=>$User['point'],
                    'vip'=>$User['vip'],
                    'auth'=>$User['auth'],
                    'cover'=>$User['cover_cdn'],
                    'region'=>explode('-', $User['region']),
                    'region_text'=>$User['region']
                ];
                $this->success('您已经绑定过，无须重复绑定',null,$data);
                exit;
            }

            // 用户不存在
            $email=$this->request->param('email','');

            if(empty($email)){
                $this->error('请填写邮箱地址');
                exit;
            }

            $check=$this->UserModel->where(['email'=>$email])->find();

            if($check){
                // 用户已经找到了，先判断是否被绑定过，再判断密码收费正确，更新语句openid
                if(!empty($check['openid'])){
                    $this->error('您输入的邮箱用户已被绑定，无法再次绑定');
                    exit;
                }

                $salt=$check['salt'];
                $repass=md5($password.$salt);
                if($repass!=$check['password']){
                    $this->error('您绑定的账号密码输入错误');
                    exit;
                }

                $data=[
                    'id'=>$check['id'],
                    'openid'=>$openid
                ];

                $result=$this->UserModel->isUpdate(true)->save($data);
                if($result===FALSE){
                    $this->error($this->UserModel->getError());
                    exit;
                }

                // 重新查询最新的数据返回
                $check=$this->UserModel->where(['email'=>$email])->find();
                $data=[
                    'id'=>$check['id'],
                    'openid'=>$check['openid'],
                    'email'=>$check['email'],
                    'nickname'=>$check['nickname'],
                    'avatar'=>$check['avatar_cdn'],
                    'sex'=>$check['sex'],
                    'sex_text'=>$check['sex_text'],
                    'province'=>$check['province'],
                    'city'=>$check['city'],
                    'district'=>$check['district'],
                    'createtime'=>$check['createtime'],
                    'content'=>$check['content'],
                    'point'=>$check['point'],
                    'vip'=>$check['vip'],
                    'auth'=>$check['auth'],
                    'cover'=>$check['cover_cdn'],
                    'region'=>explode('-',$check['region']),
                    'region_text'=>$check['region'],
                ];
                $this->success('绑定成功',null,$data);
                exit;
            }else{
                $salt=randstr(10);
                $password=md5(trim($password).$salt);
                $RegisterPoint=model('Config')->where(['key'=>'RegisterPoint'])->value('value');
                $RegisterPoint=is_numeric($RegisterPoint) ? abs($RegisterPoint) : 0;

                $data=[
                    'email'=>$email,
                    'password'=>$password,
                    'salt'=>$salt,
                    'nickname'=>$email,
                    'point'=>$RegisterPoint,
                    'vip'=>0,
                    'auth'=>0,
                    'openid'=>$openid,
                ];

                $result =$this->UserModel->validate('common/User/User')->save($data);

                if($result===FALSE){
                    $this->error($this->UserModel->getError());
                    exit;
                }else{
                    $User=$this->UserModel->where(['openid'=>$openid])->find();
                    
                    $data=[
                        'id'=>$User['id'],
                        'openid'=>$User['openid'],
                        'email'=>$User['email'],
                        'nickname'=>$User['nickname'],
                        'avatar'=>$User['avatar_cdn'],
                        'sex'=>$User['sex'],
                        'sex_text'=>$User['sex_text'],
                        'province'=>$User['province'],
                        'city'=>$User['city'],
                        'district'=>$User['district'],
                        'createtime'=>$User['createtime'],
                        'content'=>$User['content'],
                        'point'=>$User['point'],
                        'vip'=>$User['vip'],
                        'auth'=>$User['auth'],
                        'cover'=>$User['cover_cdn'],
                        'region'=>explode('-', $User['region']),
                        'region_text'=>$User['region']
                    ];

                    $this->success('注册并绑定成功',null,$data);
                    exit;
                }
            }
        }
    }

    // 基本资料修改
    public function profile(){
        if($this->request->isPost()){
            $params=$this->request->param();

            $userid=$this->request->param('userid',0);
            $user=$this->UserModel->find($userid);
            if(!$user){
                $this->error('用户不存在');
                exit;
            }

            $data=[
                'id'=>$userid,
                'nickname'=>$params['nickname'],
                'sex'=>$params['sex'],
                'content'=>$params['content'],
            ];

            $region=$this->request->param('region','');

            if(!empty($region)){
                $parentpath=$this->RegionModel->where(['code'=>$region])->value('parentpath');

                if(empty($parentpath)){
                    $this->error('您所选择的地区不存在，请重新选择');
                    exit;
                }

                // 将字符串转换为数组
                $path=explode(',',$parentpath);

                if(count($path) <= 0){
                    $this->error('您所选择的地区不存在，请重新选择');
                    exit;
                }

                // 将数组里面的值分别给到不同的变量
                list($data['province'],$data['city'],$data['district'])=$path;
            }

            // 更新数据库
            $result=$this->UserModel->isUpdate(true)->save($data);
            if($result===FALSE){
                $this->error('修改个人资料失败');
                exit;
            }else{
                // 直接查询最新的结果再返回
                $UserData=$this->UserModel->find($userid);
                $data=[
                    'id'=>$UserData['id'],
                    'openid'=>$UserData['openid'],
                    'email'=>$UserData['email'],
                    'nickname'=>$UserData['nickname'],
                    'avatar'=>$UserData['avatar_cdn'],
                    'sex'=>$UserData['sex'],
                    'sex_text'=>$UserData['sex_text'],
                    'province'=>$UserData['province'],
                    'city'=>$UserData['city'],
                    'district'=>$UserData['district'],
                    'createtime'=>$UserData['createtime'],
                    'content'=>$UserData['content'],
                    'point'=>$UserData['point'],
                    'vip'=>$UserData['vip'],
                    'auth'=>$UserData['auth'],
                    'cover'=>$UserData['cover_cdn'],
                    'region'=>explode('-', $UserData['region']),
                    'region_text'=>$UserData['region']
                ];
                $this->success('修改资料成功',null,$data);
                exit;
            }
        }
    }

    // 更新封面图片的方法
    public function cover(){
        $success=[
            'code'=>0,
            'msg'=>'',
            'data'=>null
        ];

        if($this->request->isPost()){
            // 获取用户id
            $userid=$this->request->param('userid',0);

            // 判断用户是否存在
            $user=$this->UserModel->find($userid);
            if(!$user){
                $success['code']=0;
                $success['msg']='用户不存在';
                return json($success);
            }

            $data=[
                'id'=>$userid
            ];

            if(isset($_FILES['cover']) && $_FILES['cover']['size'] > 0){
                $result=upload('cover');

                if($result===FALSE){
                    $success['code']=0;
                    $success['msg']='修改封面失败';
                    return json($success);
                }

                $data['cover']='uploads/'.$result;
            }

            $result=$this->UserModel->isUpdate(true)->save($data);
            if($result===FALSE){
                @is_file($data['cover']) && @unlink($data['cover']);

                $success['code']=0;
                $success['msg']='修改个人资料失败';
                return json($$success);
            }else{
                if(@is_file($data['cover'])){
                    $cover=ltrim($user['cover'],'/');
                    @is_file($cover) && @unlink($cover);
                }

                $UserData=$this->UserModel->find($userid);
                $data=[
                    'id'=>$UserData['id'],
                    'openid'=>$UserData['openid'],
                    'email'=>$UserData['email'],
                    'nickname'=>$UserData['nickname'],
                    'avatar'=>$UserData['avatar_cdn'],
                    'sex'=>$UserData['sex'],
                    'sex_text'=>$UserData['sex_text'],
                    'province'=>$UserData['province'],
                    'city'=>$UserData['city'],
                    'district'=>$UserData['district'],
                    'createtime'=>$UserData['createtime'],
                    'content'=>$UserData['content'],
                    'point'=>$UserData['point'],
                    'vip'=>$UserData['vip'],
                    'auth'=>$UserData['auth'],
                    'cover'=>$UserData['cover_cdn'],
                    'region'=>explode('-', $UserData['region']),
                    'region_text'=>$UserData['region']
                ];

                $success['code']=1;
                $success['msg']='修改个人资料成功';
                $success['data']=$data;
                return json($success);
            }
        }
    }

    protected function code2ession($js_code=null){
        if($js_code){
            $appid='wx966f301a05cec1ad';
            $secret='1c9c16f6725e1cccc4d66a19d21412ff';
            $url="https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$js_code&grant_type=authorization_code";

            $result=$this->https_request($url);
            $resultArr=json_decode($result,true);
            return $resultArr;
        }else{
            return false;
        }
    }

    //http请求 利用php curl扩展去发送get 或者 post请求 服务器上面一定要开启 php curl扩展
    protected function https_request($url,$data=null){
        if(function_exists('curl_init')){
            $curl=curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
            if (!empty($data)){
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($curl);
            curl_close($curl);
            return $output;
        }else{
            return false;
        }
    }
}